/**
 * Copyright &copy; 2012-2016 <a href="https://istep.lczyfz.com">Istep</a> All rights reserved.
 */
package com.lczyfz.istep.modules.race.web;

import com.lczyfz.istep.common.config.Global;
import com.lczyfz.istep.common.constants.ResourceConstants;
import com.lczyfz.istep.common.constants.SceneConstants;
import com.lczyfz.istep.common.persistence.Page;
import com.lczyfz.istep.common.utils.FormatHtmlUtil;
import com.lczyfz.istep.common.web.BaseController;
import com.lczyfz.istep.modules.race.dao.RaceScheduleTeamDao;
import com.lczyfz.istep.modules.race.dao.RaceScheduleTeamSubjectDao;
import com.lczyfz.istep.modules.race.entity.*;
import com.lczyfz.istep.modules.race.service.RaceRepertoryService;
import com.lczyfz.istep.modules.race.service.RaceScheduleService;
import com.lczyfz.istep.modules.race.service.RaceTeamService;
import com.lczyfz.istep.modules.race.service.RaceUserService;
import com.lczyfz.istep.modules.resource.entity.ResourceCtfSubject;
import com.lczyfz.istep.modules.resource.entity.ResourceCtfSubjectType;
import com.lczyfz.istep.modules.resource.entity.ResourceFile;
import com.lczyfz.istep.modules.resource.service.ResourceCtfSubjectService;
import com.lczyfz.istep.modules.resource.service.ResourceCtfSubjectTypeService;
import com.lczyfz.istep.modules.resource.service.ResourceFileService;
import com.lczyfz.istep.modules.scene.entity.SceneCtfEnvironment;
import com.lczyfz.istep.modules.scene.entity.SceneCtfEnvironmentInstance;
import com.lczyfz.istep.modules.scene.service.SceneCtfEnvironmentInstanceService;
import com.lczyfz.istep.modules.scene.service.SceneCtfEnvironmentService;
import com.lczyfz.istep.modules.sys.entity.ScheduleJob;
import com.lczyfz.istep.modules.sys.entity.User;
import com.lczyfz.istep.modules.sys.service.ScheduleJobService;
import com.lczyfz.istep.modules.sys.service.SystemService;
import com.lczyfz.istep.modules.sys.utils.UserUtils;
import com.lczyfz.istep.modules.teach.entity.TeachStudentCtfsubject;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 竞赛题库管理Controller
 * @author CY
 * @version 2017-04-24
 */
@Controller
@RequestMapping(value = "${frontPath}/race/raceLogin")
public class RaceLoginController extends BaseController {

	@Autowired
	private RaceScheduleService raceScheduleService;

	@Autowired
	private RaceUserService raceUserService;

	@Autowired
	private RaceRepertoryService raceRepertoryService;

	@Autowired
	 private ResourceCtfSubjectTypeService resourceCtfSubjectTypeService;

    @Autowired
	private RaceTeamService raceTeamService;

	@Autowired
	private RaceScheduleTeamDao raceScheduleTeamDao;

	@Autowired
	private RaceScheduleTeamSubjectDao raceScheduleTeamSubjectDao;

	@Autowired
	private  ResourceCtfSubjectService resourceCtfSubjectService;
	@Autowired
	private ResourceFileService resourceFileService;
	@Autowired
	private SceneCtfEnvironmentService sceneCtfEnvironmentService;
	@Autowired
	private SceneCtfEnvironmentInstanceService sceneCtfEnvironmentInstanceService;
	@Autowired
	private ScheduleJobService scheduleJobService;
	static  List<String> flags = new ArrayList<String>();

	public static String loginerror = "false";

	public static List<String> getFlags(){
		return  flags;
	}

	@RequestMapping(value = {"list", ""})
	public String list(RaceSchedule raceSchedule, HttpServletRequest request, HttpServletResponse response, Model model,HttpSession session) {
		model.addAttribute("time", raceScheduleService.timeValue1);
         int i = 0;
		Page<RaceSchedule> page = raceScheduleService.findPage(new Page<RaceSchedule>(request, response), raceSchedule);
		for (RaceSchedule raceSchedule1 : page.getList()){
			if (raceSchedule1.getScheduleStatus().equals("1")){
				model.addAttribute("raceSchedule",raceSchedule1);
				i++;
			}
		}
		RaceSchedule raceScheduless = raceScheduleService.scheduleStatus();
		model.addAttribute("ti",raceScheduleService.ti);
		model.addAttribute("mun", i);
		if(null==raceScheduless){
			model.addAttribute("message", "close");
			loginerror = "false";
		}

		if (loginerror.equals("true")) {
			model.addAttribute("message", "true");
			System.out.println("true");
			loginerror = "false";

		} else {
			model.addAttribute("message", "false");
			System.out.println("false");

		}

		session.invalidate();

		//return "modules/race/raceLogin";
		return "modules/race/front/login";
	}


	@RequestMapping(value = "login1")
	public String login1() {
		return "modules/race/raceLoginParticipate";
	}

	@RequestMapping(value ="login")
	public String login(String judge, String user, String paw, String repertoryId, Model model, String scheduleId, RedirectAttributes redirectAttributes, HttpServletRequest request,HttpSession session) {
//		logger.debug("istep====" + judge + "=" + user + "=" + paw + "=" + repertoryId + "=" + scheduleId);
//		System.out.println("istep====" + judge + "=" + user + "=" + paw + "=" + repertoryId + "=" + scheduleId);
		RaceSchedule raceScheduless = raceScheduleService.scheduleStatus();

		if (null==raceScheduless){
			return "redirect:" + Global.getFrontPath() + "/race/raceLogin";
		}

			if (judge != null && judge.equals("1") && raceScheduless != null){

				RaceUser ssss = (RaceUser) session.getAttribute("raceUser");

				if (ssss != null) {
					System.out.println("11---------------------" + ssss.getId());
                     RaceUser raceUser = ssss;
					RaceRepertory raceRepertory = raceRepertoryService.findRepertoryName(repertoryId);
					List<RaceCtfSubject> raceCtfSubjects = raceScheduleService.findRaceSubject(raceRepertory.getId());
					int score = 0;


					//***************************

					model.addAttribute("size", raceCtfSubjects.size());
					model.addAttribute("raceCtfSubjects", raceCtfSubjects);
					model.addAttribute("rid", raceRepertory.getId());
					List<ResourceCtfSubjectType> ctfSubjectTypeList = resourceCtfSubjectTypeService.findList(new ResourceCtfSubjectType());
					model.addAttribute("ctfSubjectTypeList", ctfSubjectTypeList);
					RaceSchedule raceSchedule = raceScheduleService.teamDetails(scheduleId);
					model.addAttribute("raceSchedule", raceSchedule);
					model.addAttribute("time", raceScheduleService.timeValue);
					model.addAttribute("userId", raceUser.getId());
					//通过team_student表拿到团队id

					System.out.println(raceUser.getId() + "-------ID");
					RaceTeam raceTeam = raceTeamService.findUserTeam(raceUser.getId());
					//通过团队id得到相应对象
					RaceTeam raceTeam1 = raceTeamService.get(raceTeam.getTeamId());
//-----------------------------赛程团队--------------------------
					List<RaceScheduleTeamSubject> raceScheduleTeamSubjects = raceScheduleTeamSubjectDao.findList(new RaceScheduleTeamSubject());
					if (raceScheduleTeamSubjects != null && raceScheduleTeamSubjects.size() != 0) {
						int team = 0;
						int schedule = 0;
						for (RaceScheduleTeamSubject raceScheduleTeamSubject : raceScheduleTeamSubjects) {

							if (raceScheduleTeamSubject.getTeamid().equals(raceTeam.getTeamId())) {
								team++;
							}

							if (raceScheduleTeamSubject.getScheduleid().equals(scheduleId)) {
								schedule++;
							}
						}
						if (schedule == 0) {
							for (RaceCtfSubject raceCtfSubject : raceCtfSubjects) {
								RaceScheduleTeamSubject raceScheduleTeamSubject = new RaceScheduleTeamSubject();
								raceScheduleTeamSubject.setScheduleid(scheduleId);
								raceScheduleTeamSubject.setSubjectid(raceCtfSubject.getId());
								raceScheduleTeamSubject.setTeamid(raceTeam.getTeamId());
								raceScheduleTeamSubject.setTeamLogo(raceTeam1.getTeamLogo());
								raceScheduleTeamSubject.setScore("0");
								raceScheduleTeamSubject.setAnsweris("0");
								raceScheduleTeamSubject.setRightandwrong("0");
								raceScheduleTeamSubjectDao.insert(raceScheduleTeamSubject);
							}
						} else {
							if (team == 0) {
								for (RaceCtfSubject raceCtfSubject : raceCtfSubjects) {
									RaceScheduleTeamSubject raceScheduleTeamSubject = new RaceScheduleTeamSubject();
									raceScheduleTeamSubject.setScheduleid(scheduleId);
									raceScheduleTeamSubject.setSubjectid(raceCtfSubject.getId());
									raceScheduleTeamSubject.setTeamid(raceTeam.getTeamId());
									raceScheduleTeamSubject.setTeamLogo(raceTeam1.getTeamLogo());
									raceScheduleTeamSubject.setScore("0");
									raceScheduleTeamSubject.setAnsweris("0");
									raceScheduleTeamSubject.setRightandwrong("0");
									raceScheduleTeamSubjectDao.insert(raceScheduleTeamSubject);
								}
							}
						}
					} else {
						for (RaceCtfSubject raceCtfSubject : raceCtfSubjects) {
							RaceScheduleTeamSubject raceScheduleTeamSubject = new RaceScheduleTeamSubject();
							raceScheduleTeamSubject.setScheduleid(scheduleId);
							raceScheduleTeamSubject.setSubjectid(raceCtfSubject.getId());
							raceScheduleTeamSubject.setTeamid(raceTeam.getTeamId());
							raceScheduleTeamSubject.setTeamLogo(raceTeam1.getTeamLogo());
							raceScheduleTeamSubject.setScore("0");
							raceScheduleTeamSubject.setAnsweris("0");
							raceScheduleTeamSubject.setRightandwrong("0");
							raceScheduleTeamSubjectDao.insert(raceScheduleTeamSubject);
						}
					}
					//  -----------------------------------------------------------------------------------------------------------------

					List<RaceScheduleTeamSubject> raceScheduleTeamSubjects1 = raceScheduleTeamSubjectDao.findTeam(raceTeam.getTeamId());
					model.addAttribute("raceScheduleTeamSubjects1", raceScheduleTeamSubjects1);
					int answeris = 0;
					for (RaceScheduleTeamSubject raceScheduleTeamSubject : raceScheduleTeamSubjects1) {
						if (raceScheduleTeamSubject.getAnsweris().equals("1")) {
							answeris++;
						}
					}
					model.addAttribute("answeris", answeris);
					//  -----------------------------------------------------------------------------------------------------------------
					List<RaceScheduleTeamSubject> raceScheduleTeamSubjects2 = raceScheduleTeamSubjectDao.findRightAndWrong(raceTeam.getTeamId());
					if (raceScheduleTeamSubjects2 != null && raceScheduleTeamSubjects2.size() != 0) {
						List<String> list = new ArrayList<String>();
						for (RaceScheduleTeamSubject raceScheduleTeamSubject : raceScheduleTeamSubjects2) {
							System.out.println("-----------" + raceScheduleTeamSubject.getScore());

							int i = Integer.parseInt(raceScheduleTeamSubject.getScore());
							score = score + i;


							list.add(raceScheduleTeamSubject.getSubjectid());
						}
						model.addAttribute("score", score);
//					   List<ResourceCtfSubject> subjects = raceScheduleTeamSubjectDao.findScore(list);
//					   int scores = 0;
//					   for (ResourceCtfSubject raceScheduleTeamSubjects3 : subjects) {
//						   scores = scores + Integer.parseInt(raceScheduleTeamSubjects3.getScore());
//					   }
						model.addAttribute("scores", score);
					}


					model.addAttribute("judge", judge);
//							model.addAttribute("user", user);
//							model.addAttribute("paw", paw);
					model.addAttribute("repertoryId", repertoryId);
					model.addAttribute("scheduleId", scheduleId);

					return "modules/race/raceLoginParticipate";



				}else {


					List<RaceUser> raceUsers = raceUserService.findUserRole();
					for (RaceUser raceUser : raceUsers) {
						if (raceUser.getLoginName().equals(user) && SystemService.validatePassword(paw, raceUser.getPassword())) {
							session.setAttribute("raceUser", raceUser);
							RaceRepertory raceRepertory = raceRepertoryService.findRepertoryName(repertoryId);
							List<RaceCtfSubject> raceCtfSubjects = raceScheduleService.findRaceSubject(raceRepertory.getId());
							int score = 0;


							//***************************

							model.addAttribute("size", raceCtfSubjects.size());
							model.addAttribute("raceCtfSubjects", raceCtfSubjects);
							model.addAttribute("rid", raceRepertory.getId());
							List<ResourceCtfSubjectType> ctfSubjectTypeList = resourceCtfSubjectTypeService.findList(new ResourceCtfSubjectType());
							model.addAttribute("ctfSubjectTypeList", ctfSubjectTypeList);
							RaceSchedule raceSchedule = raceScheduleService.teamDetails(scheduleId);
							model.addAttribute("raceSchedule", raceSchedule);
							model.addAttribute("time", raceScheduleService.timeValue);
							model.addAttribute("userId", raceUser.getId());
							//通过team_student表拿到团队id

							System.out.println(raceUser.getId() + "-------ID");
							RaceTeam raceTeam = raceTeamService.findUserTeam(raceUser.getId());
							//通过团队id得到相应对象
							RaceTeam raceTeam1 = raceTeamService.get(raceTeam.getTeamId());
//-----------------------------赛程团队--------------------------
							List<RaceScheduleTeamSubject> raceScheduleTeamSubjects = raceScheduleTeamSubjectDao.findList(new RaceScheduleTeamSubject());
							if (raceScheduleTeamSubjects != null && raceScheduleTeamSubjects.size() != 0) {
								int team = 0;
								int schedule = 0;
								for (RaceScheduleTeamSubject raceScheduleTeamSubject : raceScheduleTeamSubjects) {

									if (raceScheduleTeamSubject.getTeamid().equals(raceTeam.getTeamId())) {
										team++;
									}

									if (raceScheduleTeamSubject.getScheduleid().equals(scheduleId)) {
										schedule++;
									}
								}
								if (schedule == 0) {
									for (RaceCtfSubject raceCtfSubject : raceCtfSubjects) {
										RaceScheduleTeamSubject raceScheduleTeamSubject = new RaceScheduleTeamSubject();
										raceScheduleTeamSubject.setScheduleid(scheduleId);
										raceScheduleTeamSubject.setSubjectid(raceCtfSubject.getId());
										raceScheduleTeamSubject.setTeamid(raceTeam.getTeamId());
										raceScheduleTeamSubject.setTeamLogo(raceTeam1.getTeamLogo());
										raceScheduleTeamSubject.setScore("0");
										raceScheduleTeamSubject.setAnsweris("0");
										raceScheduleTeamSubject.setRightandwrong("0");
										raceScheduleTeamSubjectDao.insert(raceScheduleTeamSubject);
									}
								} else {
									if (team == 0) {
										for (RaceCtfSubject raceCtfSubject : raceCtfSubjects) {
											RaceScheduleTeamSubject raceScheduleTeamSubject = new RaceScheduleTeamSubject();
											raceScheduleTeamSubject.setScheduleid(scheduleId);
											raceScheduleTeamSubject.setSubjectid(raceCtfSubject.getId());
											raceScheduleTeamSubject.setTeamid(raceTeam.getTeamId());
											raceScheduleTeamSubject.setTeamLogo(raceTeam1.getTeamLogo());
											raceScheduleTeamSubject.setScore("0");
											raceScheduleTeamSubject.setAnsweris("0");
											raceScheduleTeamSubject.setRightandwrong("0");
											raceScheduleTeamSubjectDao.insert(raceScheduleTeamSubject);
										}
									}
								}
							} else {
								for (RaceCtfSubject raceCtfSubject : raceCtfSubjects) {
									RaceScheduleTeamSubject raceScheduleTeamSubject = new RaceScheduleTeamSubject();
									raceScheduleTeamSubject.setScheduleid(scheduleId);
									raceScheduleTeamSubject.setSubjectid(raceCtfSubject.getId());
									raceScheduleTeamSubject.setTeamid(raceTeam.getTeamId());
									raceScheduleTeamSubject.setTeamLogo(raceTeam1.getTeamLogo());
									raceScheduleTeamSubject.setScore("0");
									raceScheduleTeamSubject.setAnsweris("0");
									raceScheduleTeamSubject.setRightandwrong("0");
									raceScheduleTeamSubjectDao.insert(raceScheduleTeamSubject);
								}
							}
							//  -----------------------------------------------------------------------------------------------------------------

							List<RaceScheduleTeamSubject> raceScheduleTeamSubjects1 = raceScheduleTeamSubjectDao.findTeam(raceTeam.getTeamId());
							model.addAttribute("raceScheduleTeamSubjects1", raceScheduleTeamSubjects1);
							int answeris = 0;
							for (RaceScheduleTeamSubject raceScheduleTeamSubject : raceScheduleTeamSubjects1) {
								if (raceScheduleTeamSubject.getAnsweris().equals("1")) {
									answeris++;
								}
							}
							model.addAttribute("answeris", answeris);
							//  -----------------------------------------------------------------------------------------------------------------
							List<RaceScheduleTeamSubject> raceScheduleTeamSubjects2 = raceScheduleTeamSubjectDao.findRightAndWrong(raceTeam.getTeamId());
							if (raceScheduleTeamSubjects2 != null && raceScheduleTeamSubjects2.size() != 0) {
								List<String> list = new ArrayList<String>();
								for (RaceScheduleTeamSubject raceScheduleTeamSubject : raceScheduleTeamSubjects2) {
									System.out.println("-----------" + raceScheduleTeamSubject.getScore());

									int i = Integer.parseInt(raceScheduleTeamSubject.getScore());
									score = score + i;


									list.add(raceScheduleTeamSubject.getSubjectid());
								}
								model.addAttribute("score", score);
//					   List<ResourceCtfSubject> subjects = raceScheduleTeamSubjectDao.findScore(list);
//					   int scores = 0;
//					   for (ResourceCtfSubject raceScheduleTeamSubjects3 : subjects) {
//						   scores = scores + Integer.parseInt(raceScheduleTeamSubjects3.getScore());
//					   }
								model.addAttribute("scores", score);
							}


							model.addAttribute("judge", judge);
//							model.addAttribute("user", user);
//							model.addAttribute("paw", paw);
							model.addAttribute("repertoryId", repertoryId);
							model.addAttribute("scheduleId", scheduleId);

							return "modules/race/raceLoginParticipate";
						}
					}
				}
//			addMessage(redirectAttributes, "账号或密码错误");
			loginerror = "true";
			request.setAttribute("loginmessage", "sdfsdfsdf");
			return "redirect:" + Global.getFrontPath() + "/race/raceLogin";
		}else {
			request.setAttribute("loginmessage", "sdfsdfsdf");
			loginerror = "true";

			return "redirect:" + Global.getFrontPath() + "/race/raceLogin";
		}
	}

@RequestMapping(value = "fuzzyQuery")
 public  String fuzzyQuery(RaceCtfSubject raceCtfSubject, Model model, String scheduleId, String usetID, String repertoryId){
	if (raceCtfSubject.getRepertoryId()==null){
		raceCtfSubject.setRepertoryId(repertoryId);
	}
	List<ResourceCtfSubjectType> ctfSubjectTypeList=resourceCtfSubjectTypeService.findList(new ResourceCtfSubjectType());
	model.addAttribute("ctfSubjectTypeList", ctfSubjectTypeList);
	for (ResourceCtfSubjectType resourceCtfSubjectType : ctfSubjectTypeList){
		if (raceCtfSubject.getType() != null && !raceCtfSubject.getType().equals("")) {
			if (resourceCtfSubjectType.getSubjectTypeName().equals(raceCtfSubject.getType())) {
				raceCtfSubject.setType(resourceCtfSubjectType.getId());
			}
		}
	}
	RaceSchedule raceSchedule = raceScheduleService.teamDetails(scheduleId);
	model.addAttribute("raceSchedule",raceSchedule);
	List<RaceCtfSubject> rcj = raceScheduleService.findRaceSubject(raceCtfSubject.getRepertoryId());
	model.addAttribute("size", rcj.size());
	int score = 0;
	for (RaceCtfSubject raceCtfSubject1 : rcj){
		int i = Integer.parseInt(raceCtfSubject1.getScore());
		score = score + i;
	}
	model.addAttribute("score" , score);
	List<RaceCtfSubject> raceCtfSubjects = raceScheduleService.findFuzzyQuery(raceCtfSubject);
	model.addAttribute("rid",raceCtfSubject.getRepertoryId());
	model.addAttribute("raceCtfSubjects",raceCtfSubjects);
	model.addAttribute("time",raceScheduleService.timeValue);
	//=================================================================
	RaceTeam raceTeam = raceTeamService.findUserTeam(usetID);
	List<RaceScheduleTeamSubject> raceScheduleTeamSubjects1 = raceScheduleTeamSubjectDao.findTeam(raceTeam.getTeamId());
	model.addAttribute("raceScheduleTeamSubjects1",raceScheduleTeamSubjects1);
	int answeris = 0;
	for (RaceScheduleTeamSubject raceScheduleTeamSubject : raceScheduleTeamSubjects1){
		if (raceScheduleTeamSubject.getAnsweris().equals("1")){
			answeris++;
		}
	}
	model.addAttribute("answeris", answeris);
//  -----------------------------------------------------------------------------------------------------------------
	List<RaceScheduleTeamSubject> raceScheduleTeamSubjects2 = raceScheduleTeamSubjectDao.findRightAndWrong(raceTeam.getTeamId());
	if (raceScheduleTeamSubjects2 != null && raceScheduleTeamSubjects2.size()!=0) {

		List<String> list = new ArrayList<String>();
		for (RaceScheduleTeamSubject raceScheduleTeamSubject : raceScheduleTeamSubjects2) {

			System.out.println("====" + raceScheduleTeamSubject.getScore());

			list.add(raceScheduleTeamSubject.getSubjectid());
		}
		List<ResourceCtfSubject> subjects = raceScheduleTeamSubjectDao.findScore(list);
		int scores = 0;
		for (ResourceCtfSubject raceScheduleTeamSubjects : subjects) {
			scores = scores + Integer.parseInt(raceScheduleTeamSubjects.getScore());
		}
		model.addAttribute("scores", scores);
	}
    model.addAttribute("userId",usetID);

	return "modules/race/raceLoginParticipate";
};

	@ResponseBody
	@RequestMapping(value = "answer")
	public ResourceCtfSubject answer(String id){
		return  raceRepertoryService.findCtfSubject(id);
	}

	@ResponseBody
	@RequestMapping(value = "answer1")
	public ResourceCtfSubjectType answer1(String id) {
		return raceScheduleService.findCtfSubjectType(id);
	}

	public static int number = 0;
	@RequestMapping(value = "flag")
	public String flag(String repertoryId, String flag,String scheduleId, String usetID,String subjectId ) {
		System.out.println("进入flag方法：" + repertoryId + "flag:" + flag + "scheduleId:" + scheduleId + "usetID:" + usetID + "subjectId:" + subjectId);

		RaceTeam raceTeam = raceTeamService.findUserTeam(usetID);

		if (flag != null && !flag.equals("")){
			RaceScheduleTeamSubject raceScheduleTeamSubject = new RaceScheduleTeamSubject();
			raceScheduleTeamSubject.setAnswer(flag);
			raceScheduleTeamSubject.setAnsweris("1");
			raceScheduleTeamSubject.setTeamid(raceTeam.getTeamId());
			raceScheduleTeamSubject.setSubjectid(subjectId);
			if (flag.equals(resourceCtfSubjectService.get(subjectId).getAnswer())){
				raceScheduleTeamSubject.setRightandwrong("1");
				raceScheduleTeamSubject.setScore(resourceCtfSubjectService.get(subjectId).getScore());
				raceScheduleTeamSubjectDao.update(raceScheduleTeamSubject);
				if (flags.size() < 10) {
					System.out.println(number);
					if (number < 5){
						List<RaceScheduleTeamSubject> rst = raceScheduleTeamSubjectDao.getScheduleTeamtest(raceTeamService.get(raceTeam.getTeamId()).getId(), resourceCtfSubjectService.get(subjectId).getId());
						RaceSchedule raceSchedule = raceScheduleService.get(scheduleId);
						if (number == 0){
//							System.out.println("**************第一名进入");
							raceScheduleTeamSubject = rst.get(0);
							int firstScore = Integer.parseInt(raceScheduleTeamSubject.getScore()) + Integer.parseInt(raceSchedule.getPlusReluI());
							raceScheduleTeamSubject.setScore(String.valueOf(firstScore));
							raceScheduleTeamSubjectDao.update(raceScheduleTeamSubject);
						}else if (number == 1){
//							System.out.println("**************第2名进入");
							raceScheduleTeamSubject = rst.get(0);
							int firstScore = Integer.parseInt(raceScheduleTeamSubject.getScore()) + Integer.parseInt(raceSchedule.getPlusReluIi());
							raceScheduleTeamSubject.setScore(String.valueOf(firstScore));
							raceScheduleTeamSubjectDao.update(raceScheduleTeamSubject);
						} else if (number == 2) {
//							System.out.println("**************第3名进入");
							raceScheduleTeamSubject = rst.get(0);
							int firstScore = Integer.parseInt(raceScheduleTeamSubject.getScore()) + Integer.parseInt(raceSchedule.getPlusReluIii());
							raceScheduleTeamSubject.setScore(String.valueOf(firstScore));
							raceScheduleTeamSubjectDao.update(raceScheduleTeamSubject);
						} else if (number == 3) {
							raceScheduleTeamSubject = rst.get(0);
							int firstScore = Integer.parseInt(raceScheduleTeamSubject.getScore()) + Integer.parseInt(raceSchedule.getPlusReluIv());
							raceScheduleTeamSubject.setScore(String.valueOf(firstScore));
							raceScheduleTeamSubjectDao.update(raceScheduleTeamSubject);
						} else if (number == 4) {
							raceScheduleTeamSubject = rst.get(0);
							int firstScore = Integer.parseInt(raceScheduleTeamSubject.getScore()) + Integer.parseInt(raceSchedule.getPlusReluV());
							raceScheduleTeamSubject.setScore(String.valueOf(firstScore));
							raceScheduleTeamSubjectDao.update(raceScheduleTeamSubject);
						}
						number ++;
						flags.add("<p>" + raceTeamService.get(raceTeam.getTeamId()).getTeamName() + "队第" + (number) + "个提交了答案，获得" + raceScheduleTeamSubject.getScore() + "分，相关题目：" + resourceCtfSubjectService.get(subjectId).getCtfSubjectName() + "</p>");
					} else if (number >= 5) {
						flags.add("<p>" + raceTeamService.get(raceTeam.getTeamId()).getTeamName() + "队提交了答案，获得" + resourceCtfSubjectService.get(subjectId).getScore() + "分，相关题目：" + resourceCtfSubjectService.get(subjectId).getCtfSubjectName() + "</p>");
					}

				}else {
					flags.remove(0);
					flags.add("<p>" + raceTeamService.get(raceTeam.getTeamId()).getTeamName() + "队提交了答案，获得" + resourceCtfSubjectService.get(subjectId).getScore() + "分，相关题目：" + resourceCtfSubjectService.get(subjectId).getCtfSubjectName() + "</p>");

				}

			}else {
				raceScheduleTeamSubject.setRightandwrong("2");
				raceScheduleTeamSubjectDao.update(raceScheduleTeamSubject);
			}
		}
     return "redirect:"+Global.getFrontPath()+"/race/raceLogin/fuzzyQuery?scheduleId="+ scheduleId +"&usetID=" + usetID + "&repertoryId=" + repertoryId;

	}


	/**
	 * 创建ctf实例
	 *
	 * @param ctfEnvironmentId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "createCtfInstance")
	public List<String> createCtfInstance(@RequestParam(required = false) String ctfEnvironmentId) throws Exception {
		logger.debug("createCtfInstance===" + ctfEnvironmentId);

		SceneCtfEnvironmentInstance sceneCtfEnvironmentInstance = new SceneCtfEnvironmentInstance();
		SceneCtfEnvironment sceneCtfEnvironment = sceneCtfEnvironmentService.get(ctfEnvironmentId);
		sceneCtfEnvironmentInstance.setAutoDelete(SceneConstants.AUTO_DELETE_NO);

		sceneCtfEnvironmentService.createCtfInstance(sceneCtfEnvironment, sceneCtfEnvironmentInstance);

		Date orderTime = sceneCtfEnvironmentInstance.getEndDate();
		Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
		ca.setTime(orderTime); //设置时间为当前时间
		int year = ca.get(Calendar.YEAR);//获取年份
		int month = ca.get(Calendar.MONTH) + 1;//获取月份
		int day = ca.get(Calendar.DATE);//获取日
		int hour = ca.get(Calendar.HOUR_OF_DAY);//小时
		int minute = ca.get(Calendar.MINUTE);//分
		int second = ca.get(Calendar.SECOND);//秒    2017/05/16 20:27:30
		//"30 10 1 20 10 ? 2011" 2011年10月20号1点10分30秒触发任务
		String endTime = year + "/" + month + "/" + day + " " + hour + ":" + minute + ":" + second;

		List<String> list = new ArrayList<>();
//		double time=Double.parseDouble(sceneCtfEnvironment.getCtfEnvironmentTime())*60*60;
		String link = sceneCtfEnvironmentInstance.getLink();
		String instanceId = sceneCtfEnvironmentInstance.getId();
		list.add(endTime);
		list.add(link);
		list.add(instanceId);

		logger.debug("dingh========list=" + list.get(0) + " " + list.get(1) + " " + list.get(2));


		return list;
	}

	/**
	 * 增加ctf实验时间
	 */
	@ResponseBody
	@RequestMapping(value = "addTime")
	public String addTime(@RequestParam(required = false) String ctfEnvironmentId, @RequestParam(required = false) String instanceId) {

		logger.debug("dingh===" + ctfEnvironmentId + " " + instanceId);
		SceneCtfEnvironmentInstance sceneCtfEnvironmentInstance = sceneCtfEnvironmentInstanceService.get(instanceId);
		SceneCtfEnvironment sceneCtfEnvironment = sceneCtfEnvironmentService.get(ctfEnvironmentId);

		Date data = sceneCtfEnvironmentInstance.getEndDate();
		int envTime = (int) (Double.parseDouble(sceneCtfEnvironment.getIncreaseTime()) * 60);
		Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
		ca.setTime(data); //设置时间为当前时间
		ca.set(Calendar.MINUTE, ca.get(Calendar.MINUTE) + envTime);
		Date endDate = ca.getTime();
		sceneCtfEnvironmentInstance.setEndDate(endDate);

		ScheduleJob scheduleJob = scheduleJobService.findByJobName("env_instance", instanceId);
		scheduleJob.setStartDate(endDate);
		scheduleJob.setCronExpression(getCancelTime(data, envTime));

		scheduleJobService.save(scheduleJob);
		sceneCtfEnvironmentInstanceService.save(sceneCtfEnvironmentInstance);

		logger.debug("dingh===endDate=" + endDate);
		logger.debug("dingh===getCancelTime=" + getCancelTime(data, envTime));


		ca.setTime(endDate); //设置时间为当前时间
		int year = ca.get(Calendar.YEAR);//获取年份
		int month = ca.get(Calendar.MONTH) + 1;//获取月份
		int day = ca.get(Calendar.DATE);//获取日
		int hour = ca.get(Calendar.HOUR_OF_DAY);//小时
		int minute = ca.get(Calendar.MINUTE);//分
		int second = ca.get(Calendar.SECOND);//秒    2017/05/16 20:27:30
		//"30 10 1 20 10 ? 2011" 2011年10月20号1点10分30秒触发任务
		String endTime = year + "/" + month + "/" + day + " " + hour + ":" + minute + ":" + second;


		logger.debug("dingh===endTime=" + endTime);

		return endTime;

	}

	//下载附件   调用浏览器各自的下载方式
	@RequestMapping(value = "downloadDocFiles")
	public String downloadDocFiles(String ctfSubjectId, HttpServletResponse response) throws IOException, URISyntaxException {
		logger.debug("dingh===ctfSubjectId=" + ctfSubjectId);

		ArrayList<ResourceFile> totalFileList = new ArrayList<>();
		//循环该课程下所有课件
		ResourceFile resourceFile = new ResourceFile();
		resourceFile.setResourceId(ctfSubjectId);
		resourceFile.setType(ResourceConstants.fileTypeAttachment);
		List<ResourceFile> fileList = resourceFileService.findList(resourceFile);
		//循环所有课件下的所有文档
		for (ResourceFile aFileList : fileList) {
			logger.debug("==Evan==aFileList" + aFileList);
			totalFileList.add(aFileList);
		}
		logger.debug("==Evan==totalFileNum: " + totalFileList.size());

		response.setCharacterEncoding("utf-8");
		response.setContentType("APPLICATION/OCTET-STREAM");
		//设置content-disposition响应头控制浏览器以下载的形式打开文件，中文文件名要使用URLEncoder.encode方法进行编码，否则会出现文件名乱码
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
//		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode( "课程文档" + sdf.format(new Date()) + ".zip", "UTF-8"));
		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(resourceCtfSubjectService.get(ctfSubjectId).getCtfSubjectName() + "_附件" + ".zip", "UTF-8"));
		//创建输出流
		OutputStream os = response.getOutputStream();
		byte[] buf = new byte[1024];
		try {
			//ZipOutputStream类：完成文件或文件夹的压缩
			ZipOutputStream out = new ZipOutputStream(os);
			for (ResourceFile aTotalFileList : totalFileList) {
				FileInputStream fis = new FileInputStream(aTotalFileList.getLocalUrl());
				out.putNextEntry(new ZipEntry(aTotalFileList.getName()));
				int len;
				while ((len = fis.read(buf)) > 0) {
					out.write(buf, 0, len);
				}
				out.closeEntry();
				fis.close();
			}
			out.flush();
			out.close();
			logger.debug("Evan========压缩完成!!!");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	@RequestMapping(value = "test")
	public String  test(Page<RaceScheduleTeamSubject> page, Model model) {
		if (raceScheduleService.t != null) {
			raceScheduleService.t.cancel();
			raceScheduleService.timeValue = 0;
		}
		RaceSchedule raceSchedule = raceScheduleService.get("67c95e63e2e54b218b86f7c85f02967d");
		int a = 0;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String begin = sdf.format(raceSchedule.getBeginTime());
		String end = sdf.format(raceSchedule.getEndTime());
		try {
			Date beginTime = sdf.parse(begin);
			Date endTime = sdf.parse(end);
			long minutes = ( endTime.getTime() - beginTime.getTime() )/1000;
			a = (int)minutes;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		raceScheduleService.time(a);
		try {
			Thread.sleep(300);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		model.addAttribute("time", raceScheduleService.timeValue);


		return "modules/race/test";
	}






	@ResponseBody
	@RequestMapping(value = "testteam")
	public int testteam(String prolong){

		if (raceScheduleService.t != null) {
			raceScheduleService.t.cancel();
		}
       int a1 = 0;
		int time  = Integer.parseInt(prolong);
		RaceSchedule raceSchedule = raceScheduleService.get("67c95e63e2e54b218b86f7c85f02967d");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String begin = sdf.format(raceSchedule.getBeginTime());
		String end = sdf.format(raceSchedule.getEndTime());
		try {
			Date beginTime = sdf.parse(begin);
			Date endTime = sdf.parse(end);
			Long minutes =  endTime.getTime() - beginTime.getTime();
			Long a =  beginTime.getTime() + minutes + (time * 1000*60);
			Date date1 = new Date(a);
			String end1 = sdf.format(date1);
			Date date = sdf.parse(end1);
			raceSchedule.setEndTime(date);
			raceScheduleService.save(raceSchedule);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		a1 =	 (time*60) + raceScheduleService.timeValue;
		raceScheduleService.time(a1);
		return  a1;
	}





	@RequestMapping(value = "test2")
	public  String test2() {

		return "modules/race/test2";
	}


	//竞赛-进入题目
	@RequestMapping(value = "raceEnterCtfSubjectForm")
	public String raceEnterCtfSubjectForm(HttpServletRequest request, HttpServletResponse response, Model model) {
		ResourceCtfSubject resourceCtfSubject = resourceCtfSubjectService.get(request.getParameter("CtfSubjectId"));



		System.out.println("****************" + resourceCtfSubject.getCtfSubjectName());
		//进入题目中展示题目类型，将关联表中的SubjectTypeName设进CtfSubjectTypeId中
		resourceCtfSubject.setCtfSubjectTypeId(resourceCtfSubjectTypeService.get(resourceCtfSubject.getCtfSubjectTypeId()).getSubjectTypeName());
		resourceCtfSubject.setStem(FormatHtmlUtil.formatHtml(StringEscapeUtils.unescapeHtml4(resourceCtfSubject.getStem())));


		TeachStudentCtfsubject temp = new TeachStudentCtfsubject();

		User user = UserUtils.getUser();
		temp.setUserId(user.getId());
		temp.setCtfsubjectId(request.getParameter("CtfSubjectId"));
		TeachStudentCtfsubject result = resourceCtfSubjectService.findStudentCtfSubject(temp);
		if(result!=null)
			model.addAttribute("isAnswered", "true");
		else
			model.addAttribute("isAnswered", "false");
		if (resourceCtfSubject.getCtfEnvironmentId() != null && !resourceCtfSubject.getCtfEnvironmentId().equals("")) {
			SceneCtfEnvironment sceneCtfEnvironment = sceneCtfEnvironmentService.get(resourceCtfSubject.getCtfEnvironmentId());
			if (sceneCtfEnvironment.getIncreaseTimeAllow().equals("0")) {
				model.addAttribute("increaseTime", String.valueOf(Double.parseDouble(sceneCtfEnvironment.getIncreaseTime()) * 60));

				model.addAttribute("increaseNumber", sceneCtfEnvironment.getIncreaseNumber());
			}


			if (sceneCtfEnvironment.getCtfType().equals("1")) {
				String tip = sceneCtfEnvironment.getIp() + " " + sceneCtfEnvironment.getPort();
				model.addAttribute("tip", tip);
			} else {
				String time = String.valueOf(Double.parseDouble(sceneCtfEnvironment.getCtfEnvironmentTime()) * 3600);
				model.addAttribute("time", time);
				logger.debug("==Evan==time==" + time);

			}

		}


		model.addAttribute("ctfSetId", request.getParameter("ctfSetId"));
		model.addAttribute("resourceCtfSubject", resourceCtfSubject);
		model.addAttribute("judge", request.getParameter("judge"));


//		RaceUser raceUser = raceUserService.get(request.getParameter("userId"));
//		if (raceUser != null) {
//			model.addAttribute("user", raceUser.getName());
//			model.addAttribute("paw", raceUser.getPassword());
//		}


//		model.addAttribute("user", request.getParameter("user"));
//		model.addAttribute("paw", request.getParameter("paw"));

		model.addAttribute("repertoryId", request.getParameter("repertoryId"));
		model.addAttribute("scheduleId", request.getParameter("scheduleId"));
		model.addAttribute("userId", request.getParameter("userId"));
		model.addAttribute("subjectId", request.getParameter("subjectId"));
//		return "modules/race/raceEnterCtfSubjectForm";
		return "modules/race/stuEnterCtfSubjectForm1";
	}

	/**
	 * 〈方法的功能描述〉:
	 * 获取取消订单的定时任务的时间
	 *
	 * @param
	 * @return
	 * @Date 2016/12/6/11:22
	 * @author dingh
	 * @methodName
	 **/

	public String getCancelTime(Date orderTime, int afterMinute) {
		Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
		ca.setTime(orderTime); //设置时间为当前时间
		ca.set(Calendar.MINUTE, ca.get(Calendar.MINUTE) + afterMinute);
		Date time = ca.getTime(); //结果
		int year = ca.get(Calendar.YEAR);//获取年份
		int month = ca.get(Calendar.MONTH) + 1;//获取月份
		int day = ca.get(Calendar.DATE);//获取日
		int hour = ca.get(Calendar.HOUR_OF_DAY);//小时
		int minute = ca.get(Calendar.MINUTE);//分
		int second = ca.get(Calendar.SECOND);//秒
		//"30 10 1 20 10 ? 2011" 2011年10月20号1点10分30秒触发任务
		String cancelTime = second + " " + minute + " " + hour + " " + day + " " + month + " " + "? " + year;
		return cancelTime;

	}

	public Date getCancelTimeByDate(Date orderTime, int afterMinute) {
		Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
		ca.setTime(orderTime); //设置时间为当前时间
		ca.set(Calendar.MINUTE, ca.get(Calendar.MINUTE) + afterMinute);
//		ca.add(Calendar.SECOND, +30);
		Date time = ca.getTime(); //结果
		return time;
	}

}